import { configuration } from '../../config/webapi';
import { extractNumbersFromString } from '../../util/util'
import View from '../View';
import event from '../../util/NotifierManager';
import {
    INDEX_HEAT,
} from '../../util/constant';

import * as OpcUa from '../../thirdparty/opcua-webapi'

/**
 * 图扑换热站
 *
 * @export
 * @class Index2dHeat
 * @extends {View}
 */
export default class Index2dHeat extends View {

    constructor(view, main) {
        super(view, main);

        this.url = 'displays/tenant/OPCUAWebAPIss/Dev/设备监控.json'; // 图扑换热站：displays/tenant/OPCUAWebAPIss/Dev/设备监控.json
        this.key = INDEX_HEAT;

        this.tags = ['heat_chart3', 'heat_chart4',];
        this.btnTags = ['switch0_on', 'switch0_off', 'switch1_on', 'switch1_off', 'switch2_on', 'switch2_off', 'switch3_on', 'switch3_off', 'switch4_on', 'switch4_off', 'naviNode'];
        this.tags = this.tags.concat(this.btnTags);

        /** 对应着后端每一个数据 */
        this.tagMap = {
            // 上方开关
            switch0: 1, // 用于调试

            switch1: true,
            switch2: true,
            switch3: true,
            switch4: true,

            // 中间管道
            flowRateRT: 1103, // 瞬时流量
            heatRT: 39, // 瞬时热量
            valveOpenRate: 38, // 电动调节阀开度

            returnWaterPressure: 23, // 回水压力
            returnWaterTemp: 76, // 回水温度

            supplyWaterPressure: 45, // 供水压力
            supplyWaterTemp: 98, // 供水温度

            pumpFreq1: 43, // 循环泵频率No1

            returnWaterPressure2: 23, // 回水压力2
            returnWaterTemp2: 76, // 回水温度2

            flowRateRT2: 1103, // 瞬时流量2
            heatRT2: 39, // 瞬时热量2

            // 第二行
            filterPressureDiff: 10, // 过滤器差压

            supplyWaterPressure2: 45, // 供水压力
            supplyWaterTemp2: 98, // 供水温度

            supplyWaterPressure3: 45, // 供水压力
            supplyWaterTemp3: 98, // 供水温度

            pumpFreq2: 43, // 循环泵频率No1
            pumpFreq3: 43, // 循环泵频率No1
            pumpFreq4: 43, // 循环泵频率No1

            returnWaterPressure3: 23, // 回水压力3
            returnWaterTemp3: 76, // 回水温度3

            filterPressureDiff2: 10, // 过滤器差压2

            flowRateRT3: 1103, // 瞬时流量3
            heatRT3: 39, // 瞬时热量3

            filterPressureDiff3: 10, // 过滤器差压3

            flowRateRT4: 1103, // 瞬时流量4
            heatRT4: 39, // 瞬时热量4

            // 底部
            flowRateRT5: 1103, // 瞬时流量5
            heatRT5: 39, // 瞬时热量5

            flowRateRT6: 1103, // 瞬时流量6
            heatRT6: 39, // 瞬时热量6

            valveOpenRate2: 38, // 电磁阀开度

            tankLevel: 10, // 水箱液位

            flowRateRT7: 1103, // 瞬时流量7
            heatRT7: 39, // 瞬时热量7

            waterLevel: 10, // 集水坑池液位

            // 图表
            heat_chart1: [],
            heat_chart2: [],
            heat_chart3_1: [],
            heat_chart3_2: [],
            heat_chart4_1: [],
            heat_chart4_2: [],
            heat_chart4_3: [],
            heat_chart4_4: [],
        }

        window.index2dHeat = this;
    }

    onPostDeserialize() {
        if (!ht.animationplayer.g2d) {
            ht.animationplayer.g2d = this.view;
            ht.animationplayer.player2d = new ht.animationplayer.blueprintplayer(view);
            ht.animationplayer.player2d.init();
        } else {
            ht.animationplayer.player2d.init(true);
        }

        this.getDatasByTag();

        this.naviNode.a('onStateChange', (state) => {
            this.onStateChange(state);
        });

        this.btnTags.forEach((tag) => {
            this[tag].a('onClick', () => {
                this.handleClickSwitchBtn(tag);
            });
        });

        this.startRefreshTask();
        this.readAll();
    }

    handleInteractive(e) {
        const { kind, data } = e;
        if (kind == 'doubleClickBackground') {
            return;
        }
        if (kind == 'clickData') {
            this.handleClickData(data);
        }

    }

    handleClickData(data) {
        // console.log(data);
    }

    handleClickSwitchBtn(tag) {

        /** ['switch1', 'off'] */
        const tmp = tag.split('_');
        /** 1，2，3，4 */
        const switchNO = extractNumbersFromString(tmp[0]);
        const state = tmp[1];

        const onBtn = this['switch' + switchNO + '_on'];
        const offBtn = this['switch' + switchNO + '_off'];
        let nodeId = onBtn.a('nodeId');
        let value = true;
        if (state == 'on') {
            onBtn.s('state', '3'); // 按下
            offBtn.s('state', '1'); // 选中，未按下
        } else {
            offBtn.s('state', '3'); // 按下
            onBtn.s('state', '1'); // 选中，未按下
            value = false;
        }

        if (switchNO == 0) {
            const block = onBtn.getParent();
            nodeId = block.a('nodeId');
            value = value ? 1.0 : 0.0;
        }

        const rawData = this.serverDataMap[nodeId];
        console.log('-------handleClickSwitchBtn--------', { tag, switchNO, state, nodeId, value, rawData });

        const NodesToWrite = [
            {
                "NodeId": nodeId,
                // "AttributeId": 13, // 要修改的元素id，如果是修改Value，则是13，参考：src/thirdparty/opcua-webapi/cjs/opcua_attributes.js
                "AttributeId": OpcUa.Attributes.Value,
                // "IndexRange": "string",
                "Value": {
                    "UaType": rawData.Value.UaType,
                    "Value": value,
                    // "Dimensions": [
                    //     0
                    // ],
                    // "StatusCode": {
                    //     "Code": 4294967295,
                    //     "Symbol": "string"
                    // },
                    // "SourceTimestamp": "2025-01-16T09:01:25.464Z",
                    // "SourcePicoseconds": 65535,
                    // "ServerTimestamp": "2025-01-16T09:01:25.464Z",
                    // "ServerPicoseconds": 65535
                }
            }
        ];
        this.writeValue(NodesToWrite);
    }

    /******************************* OPCUA BEGIN ******************************** */

    /**
     * 更新bool类型数据状态
     *
     * @param {*} tag
     * @param {*} valueObj
     * @param {*} nodeId
     * @memberof Index2dHeat
     */
    handleUpdateBooleanNode(tag, valueObj, nodeId) {
        const children = this[tag].getChildren();
        const offBtn = children.get(0);
        const onBtn = children.get(1);
        onBtn.a('nodeId', nodeId);
        offBtn.a('nodeId', nodeId);
        if (valueObj.Value == true) {
            onBtn.s('state', '3'); // 按下
            offBtn.s('state', '1'); // 选中，未按下
        } else {
            offBtn.s('state', '3'); // 按下
            onBtn.s('state', '1'); // 选中，未按下
        }
    }

    /**
     * 更新数值类型数据状态
     *
     * @param {*} tag
     * @param {*} valueObj
     * @param {*} nodeId
     * @memberof Index2dHeat
     */
    handleUpdateNumberNode(tag, valueObj, nodeId) {
        this[tag].a('Numerical Value', valueObj.Value);

        this[tag].a('nodeId', nodeId);
    }

    /**
     * 更新图表
     *
     * @param {*} tag
     * @param {*} valueObj .Value = [0.1,...], 数值范围是0~1之间的随机数
     * @memberof Index2dHeat
     */
    handleUpdateArrayNode(tag, valueObj) {
        // console.log('-----handleUpdateArrayNode-----', { tag, valueObj })

        switch (tag) {
            case 'heat_chart1':
                this.heat_chart1.a('lineData', valueObj.Value.map((v) => { return (v * 100).toFixed(0) }));
                break;
            case 'heat_chart2':
                this.heat_chart2.a('lineData', valueObj.Value);
                break;
            case 'heat_chart3_1':
                this.heat_chart3.a('lineData1', valueObj.Value);
                break;
            case 'heat_chart3_2':
                this.heat_chart3.a('lineData2', valueObj.Value);
                break;
            case 'heat_chart4_1':
                this.heat_chart4.a('lineData1', valueObj.Value.map((v) => { return (v * 100).toFixed(0) }));
                break;
            case 'heat_chart4_2':
                this.heat_chart4.a('lineData2', valueObj.Value.map((v) => { return (v * 100).toFixed(0) }));
                break;
            case 'heat_chart4_3':
                this.heat_chart4.a('lineData3', valueObj.Value.map((v) => { return (v * 100).toFixed(0) }));
                break;
            case 'heat_chart4_4':
                this.heat_chart4.a('lineData4', valueObj.Value.map((v) => { return (v * 100).toFixed(0) }));
                break;
            default:
                break;
        }
    }

}
